package com.aikon.wht.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by haitao.wang on 2016/12/1.
 */
public class TestOfSynchronized {

     Integer k = 1;

    public Integer getK() {
        return k;
    }

    public void setK(Integer k) {
        this.k = k;
    }

    public static void main(String[] args) throws InterruptedException {
        Integer i = 1;
        int j = 1;
        TestOfSynchronized testOfSynchronized = new TestOfSynchronized();
        add1(testOfSynchronized);
        try {
            Thread t = new Thread(new T2(testOfSynchronized));
            t.start();
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (; i < 10; i++) {
            ExecutorService es = Executors.newCachedThreadPool();
            //将对象传进去.
            es.submit(new Thread(new T1(testOfSynchronized)));
            es.submit(new Thread(new T2(testOfSynchronized)));

            es.shutdown();
        }
        Thread.sleep(1000);
        System.out.println(testOfSynchronized.k);

    }

    private static void add1(TestOfSynchronized testOfSynchronized) {
        testOfSynchronized.k++;
    }

    /**
     * 加锁阻塞
     * @param t
     */
    public static synchronized void increment(TestOfSynchronized t) {
        System.out.println("M1");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.k++;
    }

    /**
     * 同类非阻塞
     * @param t
     */
    public static void incrementT(TestOfSynchronized t){
        System.out.println("M2");
        t.k++;
    }

    public static class T1 implements Runnable {

        private Integer i;

        private TestOfSynchronized testOfSynchronized;

        public T1(Integer i) {
            this.i = i;
        }

        public T1(TestOfSynchronized testOfSynchronized) {
            this.testOfSynchronized = testOfSynchronized;
        }

        @Override
        public void run() {
            //对对象的操作加锁.
            testOfSynchronized.increment(testOfSynchronized);


            System.out.println(Thread.currentThread().getName()+"        "+ testOfSynchronized.k);
        }
    }

    public static class T2 implements Runnable {

        private Integer i;

        private TestOfSynchronized testOfSynchronized;

        public T2(Integer i) {
            this.i = i;
        }

        public T2(TestOfSynchronized testOfSynchronized) {
            this.testOfSynchronized = testOfSynchronized;
        }

        @Override
        public void run() {
            //对对象的操作加锁.
            testOfSynchronized.incrementT(testOfSynchronized);

            System.out.println(Thread.currentThread().getName()+"        "+ testOfSynchronized.k);
        }
    }
}
